package com.test.datasource.dsconfig;

import com.test.dao.BaseRepositoryImpl;
import com.test.datasource.DataSourceDefine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.sql.DataSource;


@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryUniance",
        transactionManagerRef = "transactionManagerUniance",
        repositoryBaseClass = BaseRepositoryImpl.class,
        basePackages = {"com.test.dao.order"})
public class UnianceDataSourceConfigurer {
    /**
     * 注入用户数据源
     */
    private final DataSource dataSource;

    /**
     * 注入jpa配置实体
     */
    private final JpaProperties jpaProperties;

    @Autowired
    public UnianceDataSourceConfigurer(@Qualifier(DataSourceDefine.DATASOURCE_UNIANCE) DataSource dataSource,
           JpaProperties jpaProperties) {
        this.dataSource = dataSource;
        this.jpaProperties = jpaProperties;
    }
    /**
     * 配置EntityManager实体
     */
    @Bean(name = "entityManagerUniance")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryUniance(builder).getObject().createEntityManager();
    }

    /**
     * 配置EntityManager工厂实体
     */
    @Bean(name = "entityManagerFactoryUniance")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryUniance(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(dataSource)
                .properties(jpaProperties.getProperties())
                .packages("com.test.dao.order.entity")
                .persistenceUnit("uniancePersistenceUnit")
                .build();
    }


    /**
     * 配置事务
     */
    @Bean(name = "transactionManagerUniance")
    public PlatformTransactionManager transactionManagerUser(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryUniance(builder).getObject());
    }
}
